package com.lagou.xm.io.config;

import com.lagou.xm.io.enums.SQLTypeEnum;
import com.lagou.xm.io.pojo.Configuration;
import com.lagou.xm.io.pojo.MappedStatement;
import jdk.nashorn.internal.ir.ReturnNode;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.util.List;

/**
 * @author XM,Email is huangwei_xm@163.com
 * @ClassName XMLMapperBuilder
 * @Package com.lagou.xm.io.config
 * @Description 解析Mapper.xml配置文件
 * @since 2020/9/24 22:36
 * @Copyright: 训练营
 */
public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * @Description 解析mapper.xml配置文件
     * @param resource mapper.xml配置文件流
     * @author XM,Email is huangwei_xm@163.com
     * @since 2020/9/24 22:38
     */
    public void parse(InputStream resource) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(resource);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //select
        List<Element> selectList = rootElement.selectNodes("//select");
        parseSql(namespace,selectList,SQLTypeEnum.SELECT);
        // update
        List<Element> updateList = rootElement.selectNodes("//update");
        parseSql(namespace,updateList,SQLTypeEnum.UPDATE);
        // insert
        List<Element> insertList = rootElement.selectNodes("//insert");
        parseSql(namespace,insertList,SQLTypeEnum.INSERT);
        // delete
        List<Element> deleteList = rootElement.selectNodes("//delete");
        parseSql(namespace,deleteList,SQLTypeEnum.DELETE);

    }

    private void parseSql(String namespace, List<Element> noteList, SQLTypeEnum typeEnum) throws ClassNotFoundException {
        for (Element element : noteList) {
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setSqlTypeEnum(typeEnum);
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            String key = namespace + "." + id;
            mappedStatement.setId(id);
            if (resultType != null && resultType != "") {
                mappedStatement.setResultType(Class.forName(resultType));
            }
            if (parameterType != null && parameterType != "") {
                mappedStatement.setParameterType(Class.forName(parameterType));
            }
            mappedStatement.setSql(sqlText);
            configuration.getSqlStatementMap().put(key, mappedStatement);
        }
    }
}
